package com.we.utils;

import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTools {

    public static String getRegexResStr(String input, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(input);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    public static int hiveUdfRegExp(String input, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(input);
        if (matcher.find(0)) {
            return 1;
        }
        return 0;
    }

    public static int hiveUdfRegExpEx(String input, String pattern) {
        if(input != null) {
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(input);
            if (matcher.find(0)) {
                return 1;
            }
        }
        return 0;
    }

    public static String hiveUdfRegExReplace(String s, String regex, String replacement) {
        if (s == null || regex == null || replacement == null) {
            return null;
        }
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s.toString());
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, replacement);
        }
        m.appendTail(sb);

        return sb.toString();
    }

    public static String getRegexResStrInPos(String input, String pattern, int pos) {
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(input);
        if (matcher.find()) {
            MatchResult matchResult = matcher.toMatchResult();
            return matchResult.group(pos);
        }
        return null;
    }
}
